package com.golxen.framework.activity.dao;


import com.golxen.framework.db.DBManager;
import com.golxen.framework.db.dao.AbstractDaoImplByEntity;
import com.golxen.framework.event.condition.dao.entity.UserActivityConditionData;
import com.golxen.utils.LogUtil;
import com.golxen.utils.StringUtils;
import com.mysql.cj.util.LogUtils;

import java.math.BigInteger;
import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class UserActivityDaoImpl extends AbstractDaoImplByEntity<UserActivityConditionData> {

    public Map<Integer, List<UserActivityConditionData>> getUserActivityConditionDataMap(long userId,
            List<Integer> activityIdList) {
        ResultSet rs = null;
        CallableStatement call = null;
        Map<Integer, List<UserActivityConditionData>> dataMap = new ConcurrentHashMap<>();
        if (null != activityIdList && activityIdList.size() > 0) {
            String sql = "select * from t_u_activity_condition where userId=? and activityId in("
                    + StringUtils.listToString(activityIdList, ",") + ")";
            try {
                getDb().setConnName(DBManager.userDbName);
                call = getDb().getConnection().prepareCall(sql);
                call.setLong(1, userId);
                rs = call.executeQuery();
                while (rs.next()) {
                    UserActivityConditionData data = parse(rs);
                    if (!dataMap.containsKey(data.getActivityId())) {
                        dataMap.put(data.getActivityId(), new ArrayList<>());
                    }
                    dataMap.get(data.getActivityId()).add(data);
                }
            } catch (Exception e) {
                throw new RuntimeException(e);
            } finally {
                getDb().closeConnection(call, rs);
            }
        }
        return dataMap;
    }



    public List<UserActivityConditionData> getUserActivityConditionDataListByType(int activityId, int conditionType) {
        ResultSet rs = null;
        CallableStatement call = null;
        String sql = "select * from t_u_activity_condition where activityId=?  and type = ?";
        List<UserActivityConditionData> dataList = new ArrayList<>();
        try {
            getDb().setConnName(DBManager.userDbName);
            call = getDb().getConnection().prepareCall(sql);
            call.setInt(1, activityId);
            call.setInt(2, conditionType);
            rs = call.executeQuery();
            while (rs.next()) {
                UserActivityConditionData data = parse(rs);
                dataList.add(data);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            getDb().closeConnection(call, rs);
        }
        return dataList;
    }


    public UserActivityConditionData getUserActivityConditionData(int activityId, long userId, int conditionId) {
        ResultSet rs = null;
        CallableStatement call = null;
        String sql = "select * from t_u_activity_condition where activityId=? and userId=? and conditionId=?";
        try {
            getDb().setConnName(DBManager.userDbName);
            call = getDb().getConnection().prepareCall(sql);
            call.setInt(1, activityId);
            call.setLong(2, userId);
            call.setInt(3, conditionId);
            rs = call.executeQuery();
            while (rs.next()) {
                UserActivityConditionData data = parse(rs);
                return data;
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            getDb().closeConnection(call, rs);
        }
        return null;
    }


    @Override
    protected boolean addData(UserActivityConditionData data) {
        PreparedStatement call = null;
        String sql = "insert into t_u_activity_condition(userId,activityId,conditionId,value,modifyTime,param,nickName,"
                +
                "type) values (?,?,?,?,?,?,?,?)";
        try {
            getDb().setConnName(DBManager.userDbName);
            call = getDb().getConnection().prepareStatement(sql);
            int i = 1;
            call.setLong(i++, data.getUserId());
            call.setInt(i++, data.getActivityId());
            call.setInt(i++, data.getConditionId());
            call.setString(i++, data.getValue().toString());
            call.setLong(i++, data.getModifyTime());
            call.setString(i++, data.getParam());
            call.setString(i++, data.getNickName());
            call.setInt(i++, data.getType());
            return call.executeUpdate() > 0;
        } catch (Exception e) {
            logger.error(Thread.currentThread().getStackTrace()[1].getMethodName() + ":", e);
        } finally {
            getDb().closeConnection(call, null);
        }
        return false;
    }

    @Override
    protected boolean updateData(UserActivityConditionData data) {
        PreparedStatement call = null;
        String sql = "update t_u_activity_condition set value=?,modifyTime=?,param=?,nickName=?,type=? where userId=? and "
                + "activityId=? and conditionId=?";
        try {
            getDb().setConnName(DBManager.userDbName);
            call = getDb().getConnection().prepareStatement(sql);
            int i = 1;
            call.setString(i++, data.getValue().toString());
            call.setLong(i++, data.getModifyTime());
            call.setString(i++, data.getParam());
            call.setString(i++, data.getNickName());
            call.setInt(i++, data.getType());
            call.setLong(i++, data.getUserId());
            call.setInt(i++, data.getActivityId());
            call.setInt(i++, data.getConditionId());
            return call.executeUpdate() > 0;
        } catch (Exception e) {
            logger.error(Thread.currentThread().getStackTrace()[1].getMethodName() + ":", e);
        } finally {
            getDb().closeConnection(call, null);
        }
        return false;
    }

    @Override
    protected UserActivityConditionData parseData(ResultSet rs) throws SQLException {
        UserActivityConditionData data = new UserActivityConditionData();
        data.setUserId(rs.getLong("userId"));
        data.setActivityId(rs.getInt("activityId"));
        data.setConditionId(rs.getInt("conditionId"));
        String value = rs.getString("value");
        if (!StringUtils.isNullOrEmpty(value)) {
            data.setValue(new BigInteger(value));
        }
        data.setModifyTime(rs.getLong("modifyTime"));
        data.setParam(rs.getString("param"));
        data.setNickName(rs.getString("nickName"));
        data.setType(rs.getInt("type"));
        return data;
    }

    public List<UserActivityConditionData> getUserActivityConditionDataListByUserIdAndType(int activityId, long userId,
            int conditionType) {
        ResultSet rs = null;
        CallableStatement call = null;
        String sql = "select * from t_u_activity_condition where activityId=?  and userId = ? and  type = ?";
        List<UserActivityConditionData> dataList = new ArrayList<>();
        try {
            getDb().setConnName(DBManager.userDbName);
            call = getDb().getConnection().prepareCall(sql);
            call.setInt(1, activityId);
            call.setLong(2, userId);
            call.setInt(3, conditionType);
            rs = call.executeQuery();
            while (rs.next()) {
                UserActivityConditionData data = parse(rs);
                dataList.add(data);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            getDb().closeConnection(call, rs);
        }
        return dataList;
    }

    public Map<Integer, Map<Long, Map<Integer, List<UserActivityConditionData>>>> getActivityAllConditionData(
            List<Integer> activityIds) {
        ResultSet rs = null;
        CallableStatement call = null;
        Map<Integer, Map<Long, Map<Integer, List<UserActivityConditionData>>>> map = new ConcurrentHashMap<>();
        String sql = "select * from t_u_activity_condition where activityId in("
                + StringUtils.listToString(activityIds, ",") + ")";
        try {
            getDb().setConnName(DBManager.userDbName);
            call = getDb().getConnection().prepareCall(sql);
            rs = call.executeQuery();
            while (rs.next()) {
                UserActivityConditionData data = parse(rs);
                if (!map.containsKey(data.getActivityId())) {
                    map.put(data.getActivityId(), new ConcurrentHashMap<>());
                }
                Map<Long, Map<Integer, List<UserActivityConditionData>>> userConditionMap = map
                        .get(data.getActivityId());
                if (userConditionMap != null) {
                    if (!userConditionMap.containsKey(data.getUserId())) {
                        userConditionMap.put(data.getUserId(), new ConcurrentHashMap<>());
                    }
                    Map<Integer, List<UserActivityConditionData>> conditionMap = userConditionMap.get(data.getUserId());
                    if (conditionMap != null) {
                        if (!conditionMap.containsKey(data.getType())) {
                            conditionMap.put(data.getType(), new ArrayList<>());
                        }
                        conditionMap.get(data.getType()).add(data);
                    }
                }
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            getDb().closeConnection(call, rs);
        }
        return map;
    }

    public boolean batchAdd(List<UserActivityConditionData> tempAddUserActivityConditionDatas) {
        boolean result = false;
        if (tempAddUserActivityConditionDatas.size() == 0) {
            return true;
        }

        // 设置写入记录
        for (UserActivityConditionData data : tempAddUserActivityConditionDatas) {
            data.setBeginWriteTime();
        }

        String sql = "insert into t_u_activity_condition(userId,activityId,conditionId,value,modifyTime,param,nickName,"
                + "type) values (?,?,?,?,?,?,?,?)";
        getDb().setConnName(DBManager.userDbName);
        List<Map<Integer, Object>> mapList = new ArrayList<>();
        for (UserActivityConditionData data : tempAddUserActivityConditionDatas) {
            Map<Integer, Object> para = new HashMap<>();
            int i = 1;
            para.put(i++, data.getUserId());
            para.put(i++, data.getActivityId());
            para.put(i++, data.getConditionId());
            para.put(i++, data.getValue().toString());
            para.put(i++, data.getModifyTime());
            para.put(i++, data.getParam());
            para.put(i++, data.getNickName());
            para.put(i++, data.getType());
            mapList.add(para);
        }

        if (getDb().executeBatchQuery(sql, mapList) > -1) {
            // 设置写入状态
            for (UserActivityConditionData data : tempAddUserActivityConditionDatas) {
                data.setNoneOption();
            }
            result = true;
        } else { // 当批量存失败的情况下，改为单个存
            LogUtil.COMMON.warn("{} batchAdd fail {}", tempAddUserActivityConditionDatas.get(0).getUserId(), tempAddUserActivityConditionDatas.size());
            for (UserActivityConditionData data : tempAddUserActivityConditionDatas) {
                add(data);
            }
        }
        return result;
    }
    
    public boolean batchUpdate(List<UserActivityConditionData> tempAddUserActivityConditionDatas) {
        boolean result = false;
        if (tempAddUserActivityConditionDatas.size() == 0) {
            return true;
        }
        
        // 设置写时间
        for (UserActivityConditionData data : tempAddUserActivityConditionDatas) {
            data.setBeginWriteTime();
        }
        
        String sql = "update t_u_activity_condition set value=?,modifyTime=?,param=?,nickName=?,type=? where userId=? and "
                + "activityId=? and conditionId=?";
        getDb().setConnName(DBManager.userDbName);
        List<Map<Integer, Object>> mapList = new ArrayList<>();
        for (UserActivityConditionData data : tempAddUserActivityConditionDatas) {
            Map<Integer, Object> para = new HashMap<>();
            int i = 1;
            para.put(i++, data.getValue().toString());
            para.put(i++, data.getModifyTime());
            para.put(i++, data.getParam());
            para.put(i++, data.getNickName());
            para.put(i++, data.getType());
            para.put(i++, data.getUserId());
            para.put(i++, data.getActivityId());
            para.put(i++, data.getConditionId());
            mapList.add(para);
        }
        
        if (getDb().executeBatchQuery(sql, mapList) > -1) {
            // 设置写入状态
            for (UserActivityConditionData data : tempAddUserActivityConditionDatas) {
                data.setNoneOption();
            }
            result = true;
        } else { // 当批量存失败的情况下，改为单个存
            LogUtil.COMMON.warn("{} batchUpdate fail {}", tempAddUserActivityConditionDatas.get(0).getUserId(), tempAddUserActivityConditionDatas.size());
            for (UserActivityConditionData data : tempAddUserActivityConditionDatas) {
                update(data);
            }
        }
        return result;
    }

}
